package com.kl.service.ueditor.upload;

import com.kl.common.util.StringUtil;
import com.kl.common.util.UUIDUtil;
import com.kl.component.shiro.AuthorityUser;
import com.kl.component.spring.tool.SpringApplicationContextTool;
import com.kl.modular.system.dao.model.SystemMdb;
import com.kl.modular.system.service.constant.SystemConStant;
import com.kl.modular.system.service.impl.SystemMdbServiceImpl;

import com.kl.service.ueditor.define.AppInfo;
import com.kl.service.ueditor.define.BaseState;
import com.kl.service.ueditor.define.State;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;

import java.io.*;
import java.util.Date;

public class StorageManager {
	public static final int BUFFER_SIZE = 8192;

	private static SystemMdbServiceImpl systemMdbService = (SystemMdbServiceImpl)SpringApplicationContextTool.getApplicationContext().getBean("systemMdbServiceImpl");

	public StorageManager() {
	}

	public static State saveBinaryFile(byte[] data, String path) {
		File file = new File(path);

		State state = valid(file);

		if (!state.isSuccess()) {
			return state;
		}

		try {
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(file));
			bos.write(data);
			bos.flush();
			bos.close();
		} catch (IOException ioe) {
			return new BaseState(false, AppInfo.IO_ERROR);
		}

		return state;
	}

	public static State saveFileByInputStream(InputStream is, String path,
			long maxSize) {
		State state = null;

		File tmpFile = getTmpFile();

		byte[] dataBuf = new byte[ 2048 ];
		BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE);

		try {
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(tmpFile), StorageManager.BUFFER_SIZE);

			int count = 0;
			while ((count = bis.read(dataBuf)) != -1) {
				bos.write(dataBuf, 0, count);
			}
			bos.flush();
			bos.close();

			if (tmpFile.length() > maxSize) {
				tmpFile.delete();
				return new BaseState(false, AppInfo.MAX_SIZE);
			}

			state = saveTmpFile(tmpFile, path);

			state = saveMongoFile(tmpFile, path, state);

			return state;
			
		} catch (IOException e) {
		}
		return new BaseState(false, AppInfo.IO_ERROR);
	}

	public static State saveFileByInputStream(InputStream is, String path) {
		State state = null;

		File tmpFile = getTmpFile();

		byte[] dataBuf = new byte[ 2048 ];
		BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE);

		try {
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(tmpFile), StorageManager.BUFFER_SIZE);

			int count = 0;
			while ((count = bis.read(dataBuf)) != -1) {
				bos.write(dataBuf, 0, count);
			}
			bos.flush();
			bos.close();

			state = saveTmpFile(tmpFile, path);

			state = saveMongoFile(tmpFile, path, state);

			return state;
		} catch (IOException e) {
		}
		return new BaseState(false, AppInfo.IO_ERROR);
	}

	private static File getTmpFile() {
		File tmpDir = FileUtils.getTempDirectory();
		String tmpFileName = (Math.random() * 10000 + "").replace(".", "");
		return new File(tmpDir, tmpFileName);
	}

	private static State saveTmpFile(File tmpFile, String path) {
		State state = null;
		File targetFile = new File(path);

		if (targetFile.canWrite()) {
			return new BaseState(false, AppInfo.PERMISSION_DENIED);
		}
		try {
			FileUtils.moveFile(tmpFile, targetFile);
		} catch (IOException e) {
			return new BaseState(false, AppInfo.IO_ERROR);
		}

		state = new BaseState(true);
		state.putInfo( "size", targetFile.length() );
		state.putInfo( "title", targetFile.getName() );
		
		return state;
	}

	private static State valid(File file) {
		File parentPath = file.getParentFile();

		if ((!parentPath.exists()) && (!parentPath.mkdirs())) {
			return new BaseState(false, AppInfo.FAILED_CREATE_FILE);
		}

		if (!parentPath.canWrite()) {
			return new BaseState(false, AppInfo.PERMISSION_DENIED);
		}

		return new BaseState(true);
	}

	private static State saveMongoFile(File tmpFile, String path, State state) {
//		File file = new File(path);
//		MongoFile mongoFile = new MongoFile();
//		mongoFile.setId(UUIDUtil.getUniquekey());
//		mongoFile.setFileName(mongoFile.getId());
//		mongoFile.setFileSize(file.length());
//		mongoFile.setFile(file);
//		mongoFile.setOldFileName(file.getName());
//		String fileType = mongoFile.getOldFileName().substring(mongoFile.getOldFileName().lastIndexOf(".")+1);
//		mongoFile.setContentType(MongoServiceImpl.getcontentType(fileType));
//		mongoFile.setFileType(fileType);
//
//		Session session = SecurityUtils.getSubject().getSession();
//		AuthorityUser authUser = (AuthorityUser) session.getAttribute((SystemConStant.SESSION_USER_KEY));
//
//		SystemMdb systemMdb = new SystemMdb();
//		systemMdb.setFileCode(StringUtil._10_to_62(System.nanoTime(),8));
//		systemMdb.setContentType(mongoFile.getContentType());
////		systemMdb.setEnpId(authUser.getEnpId());
////		systemMdb.setOrgansId(authUser.getOrgansId());
//		systemMdb.setNewFileName(mongoFile.getId());
//		systemMdb.setFileSize(String.valueOf(mongoFile.getFileSize()));
//		systemMdb.setMdbCode(mongoFile.getId());
//		systemMdb.setMdbCname(MongoFile.MDB_FILE_TABLE_NAEM);
//		systemMdb.setFileName(file.getName());
//		systemMdb.setCreateTime(new Date());
//		systemMdb.setModifyAdminId(authUser.getId());
//		systemMdb.setModifyTime(new Date());
//		systemMdb.setEnabled(false);
//
//		boolean flag = mongoService.saveFiles("mongoFile",mongoFile);
		boolean flag = false;
		tmpFile.delete();
		//file.delete();
		if (flag) {
			//systemMdbService.insert(systemMdb);
			//state.putInfo("url", "/common/getMGFile/"+systemMdb.getFileCode()+".do");
		} else {
			new BaseState(false, AppInfo.IO_ERROR);
		}
		return state;
	}
}
